package com.ruoyi.web.controller.PhoneLogin;




import com.alibaba.fastjson.JSON;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.GoodsAttach.domain.GoodsAttach;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.QiniuCloudUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.service.PhoneLoginService;

import com.ruoyi.system.util.*;
import com.ruoyi.system.weixin.*;
import com.sun.javafx.collections.MappingChange;
import io.swagger.annotations.ApiOperation;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.spi.http.HttpContext;
import java.io.*;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Struct;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import static com.ruoyi.common.config.Global.getConfig;
import static com.ruoyi.system.util.ImageSizeUtil.byte2Base64StringFun;
import static com.ruoyi.system.util.MD5.string2MD5;
import static com.ruoyi.web.controller.PhoneLogin.WeChatJSSDKController.createNonceStr;
import static org.bouncycastle.asn1.cms.CMSObjectIdentifiers.encryptedData;


/**
 * 微信小程序操作处理
 * 
 * @author niesui
 * @date 2019-07-16
 */
@Controller
@RequestMapping("/a/data")
public class PhoneLoginController
{

	
	@Autowired
	private PhoneLoginService phoneLoginService;


	/**
	 * @author:  niesui
	 * @methodsName: a/data/procedure
	 * @description: 存储过程调用接口 不需登陆
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/procedure_t")
	@ResponseBody
	public Map<String, Object> procedure_t(
			@RequestParam(value = "p", required = true) String p,HttpServletRequest request){
		Map<String, Object> returnMap=new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			/*if(p.split("|")[0].equals("R2002004")){
				HttpSession session = request.getSession();
				session.setAttribute("oid", list.get(0).get("id"));
			}*/
			return returnMap;
		}catch (Exception e){
			returnMap.clear();
			System.out.println(e);
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}

	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/procedureList
	 * @description: 存储过程调用分页接口 需登陆
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/procedure")
	@ResponseBody
	public Map<String, Object> procedure(
			@RequestParam(value = "p", required = true) String p,
			@RequestParam(value = "uid", required = true) String uid,
			@RequestParam(value = "accesstoken", required = true) String accesstoken){
		Map<String, Object> returnMap=new HashMap<String, Object>();
		try {
			//验证accesstoken
			List<Map<String, Object>> lists=  phoneLoginService.CallShellProcedure("R2001001|"+uid+"|"+accesstoken);
			String ids=lists.get(0).get("codes").toString();
			if(ids.equals("0")){
				returnMap.put("code", 0);
				returnMap.put("errorMsg", "accesstoken验证失败");
				return returnMap;
			}
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			return returnMap;
		}catch (Exception e){
			System.out.println(e);
			returnMap.clear();
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}
	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/procedureList
	 * @description: 存储过程调用分页接口 需登陆
	 * @param:  p=R1001001|参数|参数...... k(开始) j(结束) cs(其他参数)
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/procedureList")
	@ResponseBody
	public Map<String, Object> procedureList(
			@RequestParam(value = "p", required = true) String p,@RequestParam(value = "k", required = true) int k,@RequestParam(value = "j", required = true) int j,
			@RequestParam(value = "cs", required = false) String cs){
		Map<String, Object> returnMap=new HashMap<String, Object>();
		//验证登陆信息是否正确

    //cs="3|21280|%%|0|0";


		//y验证session
		List<Map<String, Object>> list=null;
		List<Map<String, Object>> lists=null;
		if(1==1){
			try {
				String p1=p+"|1|"+cs;
				lists = phoneLoginService.CallShellProcedures(p1);
				String p2=p+"|0|"+k+"|"+j+"|"+cs;
				list =  phoneLoginService.CallShellProcedures(p2);
			}catch (Exception e){
				returnMap.put("code", 0);
				returnMap.put("errorMsg", "错误！清联系管理员！错误代码：procedureList");
				return returnMap;
			}
		}else {
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "错误！登陆超时或账号在其他地方登陆");
			return returnMap;
		}


		returnMap.put("code", 1);
		returnMap.put("currentResult", k);
		returnMap.put("totalPage", lists.get(0).get("total"));
		returnMap.put("results", list);
		return returnMap;
	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/login
	 * @description: 登陆
	 * @param:  openid nickname avater
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/login",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(
			@RequestParam(value = "openid", required = true) String openid,
			HttpServletRequest request ){
		Map<String, Object> map=new HashMap<>();
		try {
			//密钥随机生成
			UUID uuid = UUID.randomUUID();
			String key= uuid.toString();
			List<Map<String, Object>> list =phoneLoginService.CallShellProcedure("R2001001|"+openid+"|"+key);
			map=list.get(0);
			//id,nickname,avatar,school,specialty,faculty
			if(Integer.parseInt(map.get("codes").toString())==0){
				map.clear();
				map.put("code", 2);
				map.put("errorMsg", "转到注册");
			}else {
				HttpSession session= request.getSession();
				session.setAttribute("accesstoken", key);
				session.setAttribute("uid", map.get("id"));
				session.setAttribute("nickname", map.get("nickname"));
				session.setAttribute("avatar", map.get("avatar"));
				session.setAttribute("renzheng", map.get("renzheng"));
				session.setAttribute("openid", openid);
				session.setAttribute("school", map.get("school"));
				session.setAttribute("specialty", map.get("specialty"));
				session.setAttribute("faculty", map.get("faculty"));
				map.clear();
				map.put("code", 1);
				map.put("uid", session.getAttribute("uid"));
				map.put("nickname",session.getAttribute("nickname"));
				map.put("avatar", session.getAttribute("avatar"));
				map.put("renzheng", session.getAttribute("renzheng"));
				map.put("accesstoken",key);
			}
		}catch ( Exception e){
			map.clear();
			map.put("code", 0);
			map.put("errorMsg", "错误!登陆服务器超时");
		}


		return map;
	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/login
	 * @description: zhuce
	 * @param:  openid nickname avater
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/login_insert")
	@ResponseBody
	public Map<String, Object> login_insert(
			@RequestParam(value = "openid", required = true) String openid,@RequestParam(value = "nickname", required = true) String nickname,
			@RequestParam(value = "avater", required = true) String avater, HttpServletRequest request){
		UUID uuid = UUID.randomUUID();
		String key= uuid.toString();
		Map<String, Object> map=new HashMap<>();
		try {


		List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure("R2001001|"+openid+"|"+key);

		map=list.get(0);
		//id,nickname,avatar,school,specialty,faculty
		if(Integer.parseInt(map.get("codes").toString())==0){
			List<Map<String, Object>> lists =  phoneLoginService.CallShellProcedure("R2001002|"+openid+"|"+nickname+"|"+avater+"|"+key);
			map=lists.get(0);
			HttpSession session= request.getSession();
			session.setAttribute("accesstoken", key);
			session.setAttribute("uid", map.get("id"));
			session.setAttribute("nickname", map.get("nickname"));
			session.setAttribute("avatar", map.get("avatar"));
			session.setAttribute("openid", openid);
			session.setAttribute("school", map.get("school"));
			session.setAttribute("specialty", map.get("specialty"));
			session.setAttribute("faculty", map.get("faculty"));
			map.clear();
			map.put("code", 1);
			map.put("uid", session.getAttribute("uid"));
			map.put("nickname",session.getAttribute("nickname"));
			map.put("renzheng",0);
			map.put("avatar", session.getAttribute("avatar"));
			map.put("accesstoken",key);
		}else {
			HttpSession session= request.getSession();
			session.setAttribute("accesstoken", key);
			session.setAttribute("uid", map.get("id"));
			session.setAttribute("nickname", map.get("nickname"));
			session.setAttribute("avatar", map.get("avatar"));
			session.setAttribute("openid", openid);
			session.setAttribute("school", map.get("school"));
			session.setAttribute("specialty", map.get("specialty"));
			session.setAttribute("faculty", map.get("faculty"));
			map.clear();
			map.put("code", 1);
			map.put("uid", session.getAttribute("uid"));
			map.put("nickname",session.getAttribute("nickname"));
			map.put("avatar", session.getAttribute("avatar"));
			map.put("renzheng",0);
			map.put("accesstoken",key);
		}
		}catch (Exception e){
			map.clear();
			map.put("code", 0);
			map.put("errorMsg", "错误!登陆服务器超时");
		}


		return map;
	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/procedure
	 * @description: 存储过程调用接口 不需登陆
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/p_order_goods")
	@ResponseBody
	public Map<String, Object> p_order_goods(@RequestParam(value = "uid", required = true) String uid,
											 @RequestParam(value = "goods", required = true) String goods,
											 @RequestParam(value = "accesstoken", required = true) String accesstoken,
			HttpServletRequest request){
		Map<String, Object> returnMap=new HashMap<String, Object>();

		//验证token
		/*HttpSession session= request.getSession();
		if(!accesstoken.equals(session.getAttribute("accesstoken"))){
			returnMap.clear();

			returnMap.put("code", 0);
			returnMap.put("errorMsg", "登陆异常");
			return returnMap;
		}*/
		String utf8="";
		try {
			utf8 = java.net.URLDecoder.decode(goods, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//拼接商品
		String p="R2002006|"+uid+"|0|";
		/*String utf8="";
		try {
			utf8 = new String(goods.getBytes(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
		//JSONArray jsArr = JSONObject.parseArray(utf8);

		//JSONObject jsonObject = JSONObject.fromObject(goods);
		//Map<String, Object> map =jsArr;
		List<HashMap> list = JSON.parseArray(utf8, HashMap.class);
        String key="";
		for(int i=0;i<list.size();i++){
			System.out.println(list.get(i));
            Map<String, Object> maps=new HashMap<String, Object>();
            maps=list.get(i);
			key= maps.get("id").toString();
			String value= maps.get("num").toString();
			Set set = maps.entrySet();

			p+=key+","+value+"|";
        //}

		}


		p+="x";
        String p2="R2012008|"+key;
        List<Map<String, Object>> list2 =  phoneLoginService.CallShellProcedure(p2);
        System.out.println(list2.get(0).get("codes")+"list2.get(0).get(\"codes\")");
        if(list2.get(0).get("codes").toString().equals("1")) {

            try {
                List<Map<String, Object>> lists = phoneLoginService.CallShellProcedure(p);
                returnMap.put("code", 1);
                returnMap.put("results", lists);
                return returnMap;
            } catch (Exception e) {
                returnMap.clear();
                System.out.println(e);
                returnMap.put("code", 0);
                returnMap.put("errorMsg", "服务器异常");
                return returnMap;
            }
        }else{
            returnMap.clear();
            returnMap.put("code", 2);
            returnMap.put("errorMsg", "不在营业时间");
            return returnMap;
        }
	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/procedure
	 * @description: 存储过程调用接口 不需登陆
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/order_goods")
	@ResponseBody
	public Map<String, Object> order_goods(@RequestParam(value = "uid", required = true) String uid,
											 @RequestParam(value = "goods", required = true) String goods,
										     @RequestParam(value = "school_id", required = true) String school_id,
										     @RequestParam(value = "jine", required = true) String jine,
										     @RequestParam(value = "dizi", required = false) String dizi,
										     @RequestParam(value = "remarks", required = true) String remarks,
											 @RequestParam(value = "accesstoken", required = true) String accesstoken,
											 HttpServletRequest request){
		Map<String, Object> returnMap=new HashMap<String, Object>();


		String utf8="";
		try {
			utf8 = java.net.URLDecoder.decode(goods, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//拼接商品
		String p="R2006008|"+uid+"|"+remarks+"|"+school_id+"|"+jine+"|"+dizi+"|";
       // String p="R2006008|"+uid+"|"+school_id+"|"+jine+"|"+dizi+"|";
		List<HashMap> list = JSON.parseArray(utf8, HashMap.class);
        String key="";
		for(int i=0;i<list.size();i++){
			System.out.println(list.get(i));
			Map<String, Object> maps=new HashMap<String, Object>();
			maps=list.get(i);
			key= maps.get("id").toString();
			String value= maps.get("num").toString();
			Set set = maps.entrySet();
			p+=key+","+value+"|";


		}

		p+="x";
        String p2="R2012008|"+key;
        List<Map<String, Object>> list2 =  phoneLoginService.CallShellProcedure(p2);
		System.out.println(list2.get(0).get("codes")+"list2.get(0).get(codes)");
        if(list2.get(0).get("codes").toString().equals("1")){
            try {
                List<Map<String, Object>> lists =  phoneLoginService.CallShellProcedure(p);
                returnMap.put("code", 1);
                returnMap.put("results", lists);

               /* HttpSession session = request.getSession();
                session.setAttribute("oid", list.get(0).get("id"));*/

                return returnMap;
            }catch (Exception e){
                returnMap.clear();
                System.out.println(e);
                returnMap.put("code", 0);
                returnMap.put("errorMsg", "服务器异常");
                return returnMap;
            }
        }else {
            returnMap.clear();
            returnMap.put("code", 2);
            returnMap.put("errorMsg", "不在营业时间");
            return returnMap;
        }



	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/file
	 * @description: 上传图片
	 * @param:  图片
	 * @return: Map<String, Object>
	 * @date: 2019年5月5日17:42:39
	 * @throws:
	 */

	@RequestMapping(value="/file" )
	@ResponseBody
	public Map<String, Object> getUploadFilePath(HttpServletRequest request, HttpServletRequest response, HttpSession session) throws IOException {
		//获取从前台传过来得图片
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
		MultipartFile file = req.getFile("file");
		Map<String, Object> map=new HashMap<>();
		//返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
		//防止上传空文件导致奔溃
		/*MultipartFile[] fils=new MultipartFile[1];
		fils[0]=file;
		fils=byte2Base64StringFun(fils);
		file=fils[0];*/
		if (file.isEmpty()) {
			map.put("errorMsg","图片为空！");
			map.put("code",0);
			return map;
		}
		String fileName = file.getOriginalFilename();// fileName
		String imageName = UUID.randomUUID().toString();
		String filepath = "pw3q13hr9.bkt.clouddn.com";
		byte[] bytes = file.getBytes();
		QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
		try {
			// 使用base64方式上传到七牛云
			String url = qiniuUtil.put64image(bytes, imageName);
			map.put("code", "1");
			map.put("url",url);
			return map;

		} catch (Exception e) {
			e.printStackTrace();
			map.put("errorMsg","图片缓存失败！");
			map.put("code",0);
			return map;
		}


	}

	//文件夹名
	public static String select_wjjs() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");//设置日期格式
		System.out.println();// new Date()为获取当前系统时间
		return df.format(new Date());
	}

	//文件名
	public static String select_wj() {
		Date date = new Date();

		String ssc= String.valueOf(date.getTime());
		Random random = new Random();
		Integer randomFileName = random.nextInt(1000);
		ssc+=randomFileName.toString();
		return ssc;
	}
	public static int addResourceHandlers(String path2, String fileName, MultipartFile file) {
		try{
			File filepath = new File(path2,fileName);
			//判断路径是否存在，如果不存在就创建一个
			if (!filepath.getParentFile().exists()) {
				filepath.getParentFile().mkdirs();
			}
			//如果文件已存在，删除已存在的文件
			if (filepath.exists()) {
				filepath.delete();
			}
			//将上传文件保存到一个目标文件当中
			file.transferTo(new File(path2 + fileName));
			return 1;
		}catch (Exception e){
			return 0;
		}

	}


	@Autowired
	private WeChatJSSDKController weChatJSSDKController;



	private  String appids=getConfig("weixin4j.appids");

    private  String appsecret=getConfig("weixin4j.secrets");

    private  String mch_id=getConfig("weixin4j.mch_id");

    private  String MerchantKey=getConfig("weixin4j.MerchantKey");

	private  WXPay wxpay;

	@RequestMapping(value="/api/jssdk/wx-config")
	@ResponseBody
	public Map<String, Object> get_wx_config(@RequestParam(value = "uid", required = true) String uid,@RequestParam(value = "order_id", required = true) String order_id,@RequestParam(value = "total_fee", required = true) String total_fee,String ix) throws ParseException {
        //获取客户端的ip地址
        //获取本机的ip地址
		Map<String, Object> response=new HashMap<>();
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String url = addr.getHostAddress();

		//验证access_token是否在有效期
		List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure("R2005009");
		Map<String, Object> sss=list.get(0);
		String t1 = sss.get("newDate").toString();
		String t2 = getBeforeByHourTime(1);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String access_token="";
		if(sdf.parse(t1).getTime()>sdf.parse(t2).getTime()){
			access_token=sss.get("access_token").toString();
		}else {
			//access_token不在有效期
			try {
				access_token =weChatJSSDKController.getAccessToken();
				phoneLoginService.CallShellProcedure("R2005010|"+access_token);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

        //商户订单号
        String out_trade_no= "9"+order_id;
        String appId =appids;
        String body = "校园帮帮支付";
        String merchantId = mch_id;
        String tradeNo = String.valueOf(new Date().getTime());
        String nonceStr1 = createNonceStr();

        String openId = phoneLoginService.CallShellProcedure("R2006004|"+uid).get(0).get("openid").toString();
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("appid", appId);
        data.put("mch_id", merchantId);
        data.put("nonce_str", nonceStr1);
        data.put("body", body);
        data.put("out_trade_no",out_trade_no);
        data.put("total_fee", String.valueOf(total_fee));
        data.put("spbill_create_ip", url);
        data.put("notify_url", "");
        data.put("trade_type","JSAPI");
        data.put("openid", openId);
		HashMap<String, String> resultMap = new HashMap<String, String>();
        try {
            Map<String, String> rMap = wxpay.unifiedOrder(data);
            System.out.println("统一下单接口返回: " + rMap);
            String return_code = (String) rMap.get("return_code");
            String result_code = (String) rMap.get("result_code");
            String nonceStr = WXPayUtil.generateNonceStr();
            resultMap.put("nonceStr", nonceStr);
			response.put("nonceStr", nonceStr);
            Long timeStamp = System.currentTimeMillis() / 1000;
            if ("SUCCESS".equals(return_code) && return_code.equals(result_code)) {
                String prepayid = rMap.get("prepay_id");
                resultMap.put("package", "prepay_id="+prepayid);
                resultMap.put("signType", "MD5");
				response.put("package", "prepay_id="+prepayid);
				response.put("signType", "MD5");
                //这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误
                resultMap.put("timeStamp", timeStamp + "");
				response.put("timeStamp", timeStamp + "");
                //再次签名，这个签名用于小程序端调用wx.requesetPayment方法
                resultMap.put("appId",appId);
				response.put("appId",appId);
                String sign = WXPayUtil.generateSignature(resultMap, MerchantKey);
                resultMap.put("paySign", sign);
				response.put("paySign", sign);
                System.out.println("生成的签名paySign : "+ sign);
                return response;
            }else{
                return  response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  response;
        }
	}
	/**
	 * 得到当前时间的前N小时
	 * 
	 * @param
	 * @param
	 * @return
	 */

	public String getBeforeByHourTime(int ihour){
		String returnstr = "";
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - ihour);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		returnstr = df.format(calendar.getTime());
		return returnstr;
	}


	/**
	 * 返回成功xml
	 */
	private String resSuccessXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

	/**
	 * 返回失败xml
	 */
	private String resFailXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";


@RequestMapping("/wxnotify")
	public void wxnotify(HttpServletRequest request, HttpServletResponse response) {
		String resXml = "";
		InputStream inStream;
		try {

			inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}

			//WXPayUtil.getLogger().info("wxnotify:微信支付----start----");

			// 获取微信调用我们notify_url的返回信息
			String result = new String(outSteam.toByteArray(), "utf-8");
			//WXPayUtil.getLogger().info("wxnotify:微信支付----result----=" + result);

			// 关闭流
			outSteam.close();
			inStream.close();

			// xml转换为map
			Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
			boolean isSuccess = false;


			System.out.println("wxnotify:微信支付回调：修改的订单===>" + resultMap.get("out_trade_no"));
			int updateResult =0;//resultMap.get("cs");
			if (updateResult > 0) {
				System.out.println("wxnotify:微信支付回调：修改订单支付状态成功");
			} else {
				System.out.println("wxnotify:微信支付回调：修改订单支付状态失败");
			}

		} catch (Exception e) {
			System.out.println("wxnotify:支付回调发布异常："+ e);
		} finally {
			try {
				// 处理业务完毕
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} catch (IOException e) {
				System.out.println("wxnotify:支付回调发布异常:out："+ e);
			}
		}

	}

	@RequestMapping(value="/api/zf")
	@ResponseBody
	public Map<String, Object> dqsfs(
			@RequestParam(value = "jes", required = true) Integer jes,
			/*@RequestParam(value = "url", required =true ) String url,*/
			@RequestParam(value = "order_id", required = true) String order_id,
			@RequestParam(value = "uid", required =true ) String uid,
			@RequestParam(value = "lx", required =true ) String lx,
			HttpServletRequest request, HttpServletResponse response) {

		return weChatJSSDKController.zf1(jes,order_id,uid,request,response,lx);
        //return weChatJSSDKController.zf1(jes,uid,request,response,lx);
	}

	/**
	 * 获取微信小程序 session_key 和 openid
	 *
	 * @param code 调用微信登陆返回的Code
	 * @return
	 */
	@RequestMapping(value="/api/login")
	@ResponseBody
	public Map<String,Object> getSessionKeyOropenid(@RequestParam(value = "code", required = true) String code, String avatarUrl, String nickName,HttpServletRequest request) throws Exception {
/*
		Map<String,Object> map = new HashMap();
		//登录凭证不能为空
		if (code == null || code.length() == 0) {
			map.put("status", 0);
			map.put("msg", "code 不能为空");
			return map;
		}

		//小程序唯一标识   (在微信小程序管理后台获取)
		String wxspAppid = appids;
		//小程序的 app secret (在微信小程序管理后台获取)
		String wxspSecret = appsecret;
		//授权（必填）
		String grant_type = "authorization_code";

		String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
		//发送请求
		String sr = HttpClientUtil.doGets("https://api.weixin.qq.com/sns/jscode2session?"+params);
		//解析相应内容（转换成json对象）
		//JSONObject jsonObject = JSON.parseObject(sr);*/
		//String keys = phoneLoginService.CallShellProcedure("R2011003").get(0).get("key").toString();
		/*JSONObject json = JSON.parseObject(sr);
		//获取会话密钥（session_key）
		String session_key = JSON.parseObject(sr).get("session_key").toString();

		String openid = (String) json.get("openid");
		Map<String,Object> ss=login(openid,request);
		int codes=Integer.parseInt(ss.get("code").toString());
		if(codes!=2){
			return ss;
		}else {
			if(StringUtils.isNotBlank(json.getString("openid"))&&StringUtils.isNotBlank(keys)){
				//解密获取用户信息
				JSONObject userInfoJSON=WechatGetUserInfoUtil.getUserInfo(encryptedData,keys,iv);
				if(userInfoJSON!=null){
					//这步应该set进实体类
					phoneLoginService.CallShellProcedure("R2011004|"+keys);
					return login_insert(userInfoJSON.get("openId").toString(),userInfoJSON.get("nickName").toString(),
							userInfoJSON.get("avatarUrl").toString(),request);

				}else{
					JSONObject userInfoJSON2=WechatGetUserInfoUtil.getUserInfo(encryptedData,session_key,iv);
					if(userInfoJSON2!=null){
						//这步应该set进实体类
						phoneLoginService.CallShellProcedure("R2011004|"+session_key);
						return login_insert(userInfoJSON2.get("openId").toString(),userInfoJSON2.get("nickName").toString(),
								userInfoJSON2.get("avatarUrl").toString(),request);

					}
					map.clear();
					map.put("code", 0);
					map.put("errorMsg", "错误!登陆服务器超时1");

				}
			}else{
				JSONObject userInfoJSON2=WechatGetUserInfoUtil.getUserInfo(encryptedData,session_key,iv);
				if(userInfoJSON2!=null){
					//这步应该set进实体类
					phoneLoginService.CallShellProcedure("R2011004|"+session_key);
					return login_insert(userInfoJSON2.get("openId").toString(),userInfoJSON2.get("nickName").toString(),
							userInfoJSON2.get("avatarUrl").toString(),request);


				}
				map.clear();
				map.put("code", 0);
				map.put("errorMsg", "错误!session_key失效");

			}
		}*/
		Map<String,Object> map  =new HashMap<String, Object>();

		String sendGet=loginByWeixin(code); //根据code去调用接口获取用户openid和session_key
		JSONObject json = JSONObject.fromObject(sendGet);

		System.out.println("返回过来的json数据:"+json.toString());
		String sessionkey=json.get("session_key").toString(); //会话秘钥
		String openid=json.get("openid").toString(); //用户唯一标识
		Map<String,Object> ss=login(openid,request);
		int codes=Integer.parseInt(ss.get("code").toString());
		if(codes!=2){
			return ss;
		}else {
			try {
				//拿到用户session_key和用户敏感数据进行解密，拿到用户信息。
				//String decrypts = AesCbcUtil.decrypt(encryptedData, sessionkey, iv, "utf-8");//解密
				//JSONObject jsons = JSONObject.fromObject(decrypts);
				String nickNames =filterEmoji(nickName); //用户昵称
				String jsonsds = avatarUrl;//jsons.get("avatarUrl").toString(); //用户头像
				/*jsons.get("avatarUrl").toString(); //头像
				jsons.get("gender").toString();//性别
				jsons.get("unionid").toString(); //unionid
				jsons.get("city").toString(); //城市
				jsons.get("province").toString();//省份
				jsons.get("country").toString(); //国家*/
				return login_insert(openid,nickNames,jsonsds,request);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}



		map.clear();
		map.put("code", 0);
		map.put("errorMsg", "错误!登陆服务器超时2");
		return map;
	}

	public static String filterEmoji(String nick_name) {
		//nick_name 所获取的用户昵称
		if (nick_name == null) {
			return nick_name;
		}
		Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]|[\ue000-\uefff]|[|]",
				Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
		Matcher emojiMatcher = emoji.matcher(nick_name);
		if (emojiMatcher.find()) {
			//将所获取的表情转换为*
			nick_name = emojiMatcher.replaceAll("");
			return nick_name;
		}
		return nick_name;
	}


	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url 发送请求的 URL
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, Map<String, ?> paramMap) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";

		String param = "";
		Iterator<String> it = paramMap.keySet().iterator();

		while (it.hasNext()) {
			String key = it.next();
			param += key + "=" + paramMap.get(key) + "&";
		}

		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			//log.error(e.getMessage(), e);
			System.out.println(e.getMessage());
		}
		//使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	//huidiao

	/**
	 2. * 支付成功后的处理
	 3.* <p>微信支付成功后，对微信返回的信息进行校验</p>
	 4. * @return
	 5. */


	@RequestMapping(value = "/huidiao")
	@ResponseBody
	public String  huidiao(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
		System.out.println("微信支付回调");
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		String resultxml = new String(outSteam.toByteArray(), "utf-8");
		System.out.println(resultxml);

		Map<String, String> params = PayCommonUtil.doXMLParse(resultxml);
		// outSteam.close();
		//inStream.close();


		Map<String,String> return_data = new HashMap<String,String>();
		if (!PayCommonUtil.isTenpaySign(params)) {
			// 支付失败
			return_data.put("return_code", "FAIL");
			return_data.put("return_msg", "return_code不正确");
			return StringUtil.GetMapToXML(return_data);
		} else {
			System.out.println("===============付款成功==============");
			// ------------------------------
			String openids = params.get("openid");
			String total_fee = params.get("total_fee");
			double v = Double.valueOf(total_fee) / 100;
			String tradeNo = params.get("transaction_id");
			String out_trade_no = params.get("out_trade_no");
			List<Map<String, Object>> lists =  phoneLoginService.CallShellProcedure("R2009007|"+openids+"|"+tradeNo+"|"+out_trade_no+"|"+total_fee);		
			/*HttpSession session = request.getSession();
			String oid=session.getAttribute("oid").toString();
			List<Map<String, Object>> listss=  phoneLoginService.CallShellProcedure("R2016006|"+openids+"|"+oid+"|"+total_fee);
*/

			return_data.put("return_code", "SUCCESS");
			return_data.put("return_msg", "OK");
			return StringUtil.GetMapToXML(return_data);
		}
	}

	/**
	 * 获取微信小程序 session_key 和 openid
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value="/api/getQRcode")
	@ResponseBody
	public Map<String,Object> getQRcode(@RequestParam(value = "uid", required = true) String uid,@RequestParam(value = "page", required = true) String page ) throws Exception {

		Map<String,Object> map = new HashMap();
		Map<String, Object> params = new HashMap<>();
		params.put("scene", uid);  //参数
		params.put("page",page); //位置
		params.put("width",430);
		List<Map<String, Object>> listss =  phoneLoginService.CallShellProcedure("R2011002|"+uid);
		Map<String, Object> ssss=listss.get(0);
		String t1s = ssss.get("ss").toString();

		if(!t1s.equals("0")){
			map.put("code", "1");
			map.put("url",t1s);
			return map;
		}

		CloseableHttpClient httpClient = HttpClientBuilder.create().build();

		//验证access_token是否在有效期
		List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure("R2005009");
		Map<String, Object> sss=list.get(0);
		String t1 = sss.get("newDate").toString();
		String t2 = getBeforeByHourTime(2);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String access_token="";
		if(sdf.parse(t1).getTime()>sdf.parse(t2).getTime()){
				//access_token在有效期
			access_token=sss.get("access_token").toString();
		}else {
				//access_token不在有效期
			access_token = weChatJSSDKController.getAccessToken();
			phoneLoginService.CallShellProcedure("R2005010|"+access_token);
		}

		HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);  // 接口
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
		String body = JSON.toJSONString(params);           //必须是json模式的 post
		StringEntity entity;
		entity = new StringEntity(body);
		entity.setContentType("image/png");

		httpPost.setEntity(entity);
		HttpResponse response;

		response = httpClient.execute(httpPost);
		InputStream inputStream = response.getEntity().getContent();
		String imageName = UUID.randomUUID().toString();
		MultipartFile file = new MockMultipartFile(imageName+".jpg",imageName+".jpg","", inputStream);




		byte[] bytes = file.getBytes();
		QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
		try {
		// 使用base64方式上传到七牛云
			String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file);
	    	//String url = qiniuUtil.put64image(bytes, imageName);
			phoneLoginService.CallShellProcedure("R2011001|"+uid+"|"+getConfig("weixin4j.dz")+avatar);
		    map.put("code", "1");
		    map.put("url",getConfig("weixin4j.dz")+avatar);
		    return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("errorMsg","图片缓存失败！");
			map.put("code",0);
			return map;
		}

	}


/*	*//*
	@RequestMapping("/login_by_weixin")
	@ResponseBody
	public Map loginByWeixin(String code, String encryptedData, String iv, HttpServletRequest request)
	{
		Map<String,Object> map  =new HashMap<String, Object>();

		String sendGet=loginByWeixin(code); //根据code去调用接口获取用户openid和session_key
		JSONObject json = JSON.parseObject(sendGet);
		//JSONObject json = JSONObject.fromObject(sendGet);
		System.out.println("返回过来的json数据:"+json.toString());
		String sessionkey=json.get("session_key").toString(); //会话秘钥
		String openid=json.get("openid").toString(); //用户唯一标识
		try{
			//拿到用户session_key和用户敏感数据进行解密，拿到用户信息。
			String decrypts= AesCbcUtil.decrypt(encryptedData,sessionkey,iv,"utf-8");//解密
			JSONObject jsons = JSON.parseObject(decrypts);
			String nickName=jsons.get("nickName").toString(); //用户昵称
			String jsonsds=jsons.get("avatarUrl").toString(); //用户头像
			jsons.get("avatarUrl").toString(); //头像
			jsons.get("gender").toString();//性别
			jsons.get("unionid").toString(); //unionid
			jsons.get("city").toString(); //城市
			jsons.get("province").toString();//省份
			jsons.get("country").toString(); //国家
		}catch (Exception e) {
			e.printStackTrace();
		}
	}*/
@RequestMapping(value="/api/tz")
@ResponseBody
public void getQRcode(){
	try {

		fxx_now( "20467","ssddfsdfdsfdsfdsd","asdasdsadsa" );
		//fxx_now("20013","nsnb1233243243242","您的订单已经被接单，请耐心等待！");
	} catch (Exception e) {
		e.printStackTrace();
	}
}


     /**微信提醒
	 * @param
   	 * @param ddbh 订单编号
   	 * @param nr 内容
	 * @return User
	 */

	public String fxx_now(String idss,String ddbh,String nr) throws ParseException {
        String mb="Gwtx49Ceq47hbGM5jbWSe21eVArKYRlcHXpzjJ14O60";
        String ps="R2012009|"+idss;
 		List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(ps);
		String openids=list.get(0).get("openid").toString();
		String ps2="R2013002|"+idss;
        String  formid=phoneLoginService.CallShellProcedure(ps2).get(0).get("codes").toString();
		Map<String, TemplateData> map = new HashMap<>();
		map.put("keyword1", new TemplateData(ddbh));
		map.put("keyword2", new TemplateData(getBeforeByHourTime(0)));
		map.put("keyword3", new TemplateData(nr));
		com.alibaba.fastjson.JSONObject js =sendTemplateMessage(openids,mb , "pages/index/index", formid, map);
		return "";
	}
	public static void main(String[] args){
          Map<String, Object> map=new HashMap<>();
		map.put("codes",1);
		try {
			if(map.get("codes").toString().equals("1")){
				System.out.println(111111);
			}else {
				System.out.println(222222);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}



	/**
	 *微信登录业务实现类:
	 * @param
	 * @return User
	 */

	public String loginByWeixin(String code) {
		Map<String, Object> map = new HashMap<String, Object>();
		//小程序唯一标识   (在微信小程序管理后台获取)
		//小程序唯一标识   (在微信小程序管理后台获取)
		String wxspAppid = appids;
		//小程序的 app secret (在微信小程序管理后台获取)
		String wxspSecret = appsecret;
		//授权（必填）
		String grant_type = "authorization_code";

		String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
		String urlss="https://api.weixin.qq.com/sns/jscode2session"; //获取用户的openid和session_key
		//注意这个是 WeChatTool.wxspAppid 是微信小程序的appid 从微信小程序后台获取 WeChatTool.wxspSecret 这个也一样，我这里是用了常量来进行保存方便多次使用
		String sendGet = Httprequests.sendGet(urlss, params); //发起请求拿到key和openid
		return sendGet;
	}


	/**
	 * @author:  niesui
	 * @methodsName: a/data/p_order_qd
	 * @description: 抢单
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/p_order_qd")
	@ResponseBody
	public Map<String, Object> p_order_qd(
			@RequestParam(value = "p", required = true) String p){
		Map<String, Object> returnMap=new HashMap<String, Object>();

		try {
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			if(list.get(0).get("codes").toString().equals("1")){
				try{
					fxx_now(list.get(0).get("user_id").toString(),list.get(0).get("orderid").toString(),"您的订单已经被接单，请耐心等待！");
				}catch (Exception e){
					System.out.println("通知失败，您的订单已经被接单，请耐心等待！"+e);
				}

			}
			return returnMap;
		}catch (Exception e){
			returnMap.clear();
			System.out.println(e);
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}

	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/p_order_qd
	 * @description: 骑手出库
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/p_order_qsck")
	@ResponseBody
	public Map<String, Object> p_order_qsck(
			@RequestParam(value = "p", required = true) String p){
		Map<String, Object> returnMap=new HashMap<String, Object>();

		try {
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			if(list.get(0).get("codes").toString().equals("1")){
				try{
					fxx_now(list.get(0).get("fxx_now").toString(),list.get(0).get("orderid").toString(),"您的订单已出库，骑手正飞奔而来！");
				}catch (Exception e){
					System.out.println("通知失败，您的订单已出库，骑手正飞奔而来！"+e);
				}
			}
			return returnMap;
		}catch (Exception e){
			returnMap.clear();
			System.out.println(e);
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}

	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/p_order_qd
	 * @description: 骑手确认送达
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/p_order_ddsd")
	@ResponseBody
	public Map<String, Object> p_order_ddsd(
			@RequestParam(value = "p", required = true) String p){
		Map<String, Object> returnMap=new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			if(list.get(0).get("codes").toString().equals("1")){
				try{
					fxx_now(list.get(0).get("user_id").toString(),list.get(0).get("orderid").toString(),"您的订单已送达，请下楼接单！");
				}catch (Exception e){
					System.out.println("通知失败，您的订单已送达，请下楼接单！"+e);
				}

			}
			return returnMap;
		}catch (Exception e){
			returnMap.clear();
			System.out.println(e);
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}

	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/p_order_qd
	 * @description: 用户确认送达
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/p_order_qrsh")
	@ResponseBody
	public Map<String, Object> p_order_qrsh(
			@RequestParam(value = "p", required = true) String p){
		Map<String, Object> returnMap=new HashMap<String, Object>();

		try {
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			if(list.get(0).get("codes").toString().equals("1")){
				try{
					fxx_now(list.get(0).get("user_id").toString(),list.get(0).get("orderid").toString(),"您接的（订单编号）订单已被客户确认收货！");

				}catch (Exception e){
					System.out.println("通知失败，您接的（订单编号）订单已被客户确认收货！"+e);
				}

			}
			return returnMap;
		}catch (Exception e){
			returnMap.clear();
			System.out.println(e);
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}

	}

	/**
	 * @author:  niesui
	 * @methodsName: a/data/p_order_qd
	 * @description: 退款
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/p_order_sqtk")
	@ResponseBody
	public Map<String, Object> p_order_sqtk(
			@RequestParam(value = "p", required = true) String p){
		Map<String, Object> returnMap=new HashMap<String, Object>();

		try {
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			if(list.get(0).get("codes").toString().equals("1")){
				try{
					fxx_now(list.get(0).get("user_id").toString(),list.get(0).get("orderid").toString(),"您接的（订单编号）订单已被用户申请退款！");
				}catch (Exception e){
					System.out.println("通知失败，您接的（订单编号）订单已被用户申请退款！"+e);
				}

			}
			return returnMap;
		}catch (Exception e){
			returnMap.clear();
			System.out.println(e);
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}

	}
	/**
	 * @author:  niesui
	 * @methodsName: a/data/p_order_fbdd
	 * @description: 发布订单
	 * @param:  p=R2001001|参数|参数。。。
	 * @return: Map<String, Object>
	 * @date: 2019年7月16日11:52:39
	 * @throws:
	 */
	@RequestMapping(value="/p_order_fbdd")
	@ResponseBody
	public Map<String, Object> p_order_fbdd(
			@RequestParam(value = "p", required = true) String p){
		//p="R2002005|21456|15289|9.5|5002|0";
		Map<String, Object> returnMap=new HashMap<String, Object>();
           System.out.println("===============发布订单===================");
		try {
			List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure(p);
			returnMap.put("code", 1);
			returnMap.put("results", list);
			System.out.println("===============返回1===================");
			try{
				if(list.get(0).get("sfss").toString().equals("1")){
					System.out.println("===============打印1===================");
					String ppd="R2012010|"+list.get(0).get("bl_orderid").toString();
					List<Map<String, Object>> lists =  phoneLoginService.CallShellProcedure(ppd);
					Map<String, Object> mapp=new HashMap<String, Object>();
					mapp=lists.get(0);
					String SN=mapp.get("sn").toString();
					System.out.println("===============打印2"+SN+"===================");
					String content;
					/*content = "<CB>订单"+mapp.get("id")+"</CB><BR>";*/
					content = "校园帮帮";
					content += "订单编号："+mapp.get("orderid")+"<BR>";
					content += "名称　　　　　       数量  金额<BR>";
					content += "-------------------------------<BR>";
					//遍历
					List<Map<String, Object>> listss =  phoneLoginService.CallShellProcedure("R2002009|"+list.get(0).get("bl_orderid").toString());
					System.out.println("===============打印3"+listss.size()+"===================");
					for (int s=0;s<listss.size();s++){
						Map<String, Object> sp_noe=new HashMap<>();
						sp_noe=listss.get(s);
						String nas=sp_noe.get("goods_name").toString();
						//12
						int as=nas.length();
						if(as<12){
                            content += ""+nas+multipleSpaces(12-as)+" "+sp_noe.get("num").toString()+"  "+(Double.parseDouble(sp_noe.get("num").toString()) *Double.parseDouble(sp_noe.get("goods_nowprice").toString()))+"<BR>";

                        }else {
                            content += ""+nas+"<BR>"+multipleSpaces(12)+" "+sp_noe.get("num").toString()+"  "+(Double.parseDouble(sp_noe.get("num").toString()) *Double.parseDouble(sp_noe.get("goods_nowprice").toString()))+"<BR>";

                        }
                        					}
					content += "---------------------------------<BR>";
					content += "合计："+mapp.get("jine")+"元<BR>";
					content += "送货地点："+mapp.get("remarks")+"<BR>";
					content += "宿舍楼："+mapp.get("dorm_name")+"<BR>";
					content += "收货人："+mapp.get("realname")+"<BR>";
					content += "手机号："+mapp.get("mobile")+"<BR>";
					content += "订单时间："+mapp.get("modifyDate")+"<BR>";
					if (!mapp.get("bl_pd").toString().equals("0")){
						content += "其他信息：【"+mapp.get("zname")+"】"+mapp.get("remarks2")+"<BR>";
					}
					Dayinji dass=new Dayinji();
					System.out.println("===============打印4===================");
					String method1 = dass.printss(SN,content);
					System.out.println("method1"+method1);
				}
			}catch (Exception e){
				System.out.println("===============打印1报错===================");
				System.out.println(e);
			}

			return returnMap;
		}catch (Exception e){
			System.out.println("===============发布1报错===================");
			System.out.println(e);
			returnMap.clear();
			returnMap.put("code", 0);
			returnMap.put("errorMsg", "服务器异常");
			return returnMap;
		}

	}
	public String multipleSpaces(int n){
		String output = "";
		n=n*2;

		for(int i=0; i<n; i++)
			output += " ";

		return output;
	}


	private static String SEND_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=";

	/**
	 * 发送模板消息sendTemplateMessage
	 * 小程序模板消息,发送服务通知
	 * @param touser 接收者（用户）的 openid
	 * @param template_id 所需下发的模板消息的id
	 * @param page 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
	 * @param formid 表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
	 * @return
	 */
	public com.alibaba.fastjson.JSONObject sendTemplateMessage(String touser, String template_id, String page, String formid, Map<String,TemplateData> map) throws ParseException {


		//验证access_token是否在有效期
		List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure("R2005009");
		Map<String, Object> sss=list.get(0);
		String t1 = sss.get("newDate").toString();
		String t2 = getBeforeByHourTime(1);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String access_token="";
		if(sdf.parse(t1).getTime()>sdf.parse(t2).getTime()){
			access_token=sss.get("access_token").toString();
		}else {
			//access_token不在有效期
			try {
				access_token =weChatJSSDKController.getAccessToken();
				phoneLoginService.CallShellProcedure("R2005010|"+access_token);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		sendTemplateMessage sendTemplateMessage = new sendTemplateMessage();
		//拼接数据
		sendTemplateMessage.setTouser(touser);
		sendTemplateMessage.setTemplate_id(template_id);
		//sendTemplateMessage.setPage(page);
		sendTemplateMessage.setForm_id(formid);
		sendTemplateMessage.setData(map);
		//sendTemplateMessage.setEmphasis_keyword("yj9iTC9SKM7sUzAjNRi6ZfNsN7ZDI7J2");
		String json = com.alibaba.fastjson.JSONObject.toJSONString(sendTemplateMessage);

		String ret = sendPost(SEND_TEMPLATE_MESSAGE + access_token, json);
		return JSON.parseObject(ret);
	}

	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("Accept", "application/json");
			conn.setRequestProperty("Content-Type", "application/json");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}





	/**
	 * 验证签名
	 *
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String[] arr = new String[] { WECHAT_TOKEN, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排序
		// Arrays.sort(arr);
		sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 *
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 *
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];
		String s = new String(tempArr);
		return s;
	}
	public static void sort(String a[]) {
		for (int i = 0; i < a.length - 1; i++) {
			for (int j = i + 1; j < a.length; j++) {
				if (a[j].compareTo(a[i]) < 0) {
					String temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}
	}

	// 与接口配置信息中的Token要一致
	private static String WECHAT_TOKEN = "l00itzphwhy2ei86ppib4oogyx8g5b63";

	@RequestMapping("/api/checkToken")
	public void gets(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("=====================收到消息1=====================");
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		System.out.println("====================="+isGet+"=====================");
		PrintWriter print;
		if (isGet) {
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 随机字符串
			String echostr = request.getParameter("echostr");
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (signature != null && checkSignature(signature, timestamp, nonce)) {
				try {
					print = response.getWriter();
					print.write(echostr);
					print.flush();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{

			}
		}else {
			System.out.println("=====================收到消息2=====================");
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			// 接收消息并返回消息
			String result = acceptMessage(request, response);

			System.out.println("result"+result);
			// 响应消息
			PrintWriter out = response.getWriter();
			out.print(result);
			out.close();

		}
	}

	public String acceptMessage(HttpServletRequest request, HttpServletResponse response) {
//        {CreateTime=1548042266, Event=user_enter_tempsession, ToUserName=gh_e6198220cbff,
//                FromUserName=oZvme4q2Oi7Dz3FChXc43kqw28, MsgType=event, SessionFrom=wxapp}
		String respMessage = "";
		System.out.println("=====================进入消息=====================");
		try {
            //"ToUserName": "toUser",
            //"FromUserName": "fromUser",
            //"CreateTime": 1482048670,
             //"MsgType": "event",
            // "Event": "user_enter_tempsession",
             //"SessionFrom": "sessionFrom"
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			System.out.println(">>>>>>>>>>>>>"+requestMap);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型

			//此处我默认为直接人工服务  可根据实际业务调整
			return switchCustomerService(fromUserName,toUserName,requestMap);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}


	/***
	 * 文档地址：https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/conversation.html
	 * 转发至人工客服 现在默认都为人工客服
	 */
	public  String switchCustomerService  (String fromUserName, String toUserName,Map requestMap)throws Exception{

		TextMessage textMessage=new TextMessage();
		textMessage.setToUserName(toUserName );   //这里的ToUserName  是刚才接收xml中的FromUserName
		textMessage.setFromUserName(fromUserName);   //这里的FromUserName 是刚才接收xml中的ToUserName  这里一定要注意，否则会出错
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setContent(requestMap.get("Content").toString());
		textMessage.setMsgType("event");
        textMessage.setEvent("user_enter_tempsession");
        textMessage.setSessionFrom(requestMap.get("SessionFrom").toString());

		String xml=MessageUtil.textMessageToXml(textMessage);


		return xml;
	}

	@RequestMapping(value="/p_date_qd")
	@ResponseBody
	public Map<String, Object> p_date_qd(
			@RequestParam(value = "p", required = true) String p,@RequestParam(value = "uid", required = true) String uid){
		//p="[{\"isToday\":\"20190901\",\"dateNum\":1,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190902\",\"dateNum\":2,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190903\",\"dateNum\":3,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190904\",\"dateNum\":4,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190905\",\"dateNum\":5,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190906\",\"dateNum\":6,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190907\",\"dateNum\":7,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190908\",\"dateNum\":8,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190909\",\"dateNum\":9,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190910\",\"dateNum\":10,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190911\",\"dateNum\":11,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190912\",\"dateNum\":12,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190913\",\"dateNum\":13,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190914\",\"dateNum\":14,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190915\",\"dateNum\":15,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190916\",\"dateNum\":16,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190917\",\"dateNum\":17,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190918\",\"dateNum\":18,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190919\",\"dateNum\":19,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190920\",\"dateNum\":20,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190921\",\"dateNum\":21,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190922\",\"dateNum\":22,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190923\",\"dateNum\":23,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190924\",\"dateNum\":24,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190925\",\"dateNum\":25,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190926\",\"dateNum\":26,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190927\",\"dateNum\":27,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190928\",\"dateNum\":28,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190929\",\"dateNum\":29,\"weight\":5,\"is_qian\":0},{\"isToday\":\"20190930\",\"dateNum\":30,\"weight\":5,\"is_qian\":0}]";
		JSONArray jsonss = JSONArray.fromObject(p);

		List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure("R2015009|"+uid+"|"+JSONObject.fromObject(jsonss.get(10)).get("isToday"));
		List<Map<String, Object>> lists=new ArrayList<>();
		Map<String, Object> returnMaps=new HashMap<String, Object>();
		int dateNum=1;
		int sss=0;
		for (int i=0;i<jsonss.size();i++){
			Map<String, Object> returnMap=new HashMap<String, Object>();
			JSONObject jsonsss =JSONObject.fromObject(jsonss.get(i));
			try{
				if(jsonsss.get("isToday").equals("0")){

				}
			}catch (Exception e){
				returnMap.put("is_qian",0);
				lists.add(i,returnMap);
				continue;
			}

			for (int r=0;r<list.size();r++){
				if(jsonsss.get("isToday").equals(list.get(r).get("date_s"))){
					sss=1;

				}

			}

			if(sss==1){
				returnMap.put("isToday",jsonsss.get("isToday"));
				returnMap.put("dateNum",dateNum);
				returnMap.put("weight",5);
				returnMap.put("is_qian",1);
				lists.add(returnMap);
			}else {
				returnMap.put("isToday",jsonsss.get("isToday"));
				returnMap.put("dateNum",dateNum);
				returnMap.put("weight",5);
				returnMap.put("is_qian",0);
				lists.add(returnMap);
			}
			sss=0;
			dateNum++;
		}


		returnMaps.put("code", 1);
		returnMaps.put("data", lists);
		return returnMaps;

	}

	@RequestMapping(value="/p_dates_lw")
	@ResponseBody
	public Map<String, Object> p_dates_lw(
			@RequestParam(value = "datas", required = true) String datas,@RequestParam(value = "uid", required = true) String uid){
			//JSONArray jsonss = JSONArray.fromObject(p);

		List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure("R2016009|"+uid+"|"+datas);
		List<Map<String, Object>> lists =  phoneLoginService.CallShellProcedure("R2016010");

        for(int i=0,s=list.size();i<s;i++){
			Map<String, Object> maps=list.get(i);

			if(Integer.parseInt(maps.get("sign_ts").toString())==0 && i==0){
				maps.put("sign_ts",1);
				list.set(i,maps);
			}else if(Integer.parseInt(maps.get("sign_ts").toString())==0) {
				maps.put("sign_ts",Integer.parseInt(list.get(i-1).get("sign_ts").toString())+1);
				list.set(i,maps);
			}
			for(int i2=0,s2=lists.size();i2<s2;i2++){
				if(list.get(i).get("sign_ts").equals(lists.get(i2).get("days"))){
					int jinb=(Integer.parseInt(lists.get(i2).get("sssss").toString()));
					maps.put("lws",jinb);
					list.set(i,maps);
					break;
				}
			}
		}
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = format1.parse(datas);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int marchs = c.get(Calendar.MARCH)+1;
		int dayss = c.get(Calendar.DAY_OF_MONTH);
		List<Map<String, Object>> newList=new ArrayList<>();
		if (dayss<6) {
			newList = list.subList(0, 5);
		}else if (dayss<11) {
			newList = list.subList(5, 10);
		}else if (dayss<16) {
			newList = list.subList(10, 15);
		}else if (dayss<21) {
			newList = list.subList(15, 20);
		}else if (dayss<26) {
			newList = list.subList(20, 25);
		}else if (dayss<31) {
			newList = list.subList(25, 30);
		}else if (dayss<32) {
			newList = list.subList(30, 32);
		}

		Map<String, Object> returnMaps=new HashMap<String, Object>();



		returnMaps.put("code", 1);
		returnMaps.put("data", newList);
		return returnMaps;

	}


}
